package net.maku.qdd.common.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Excel工具类
 */
public class ExcelUtils {

    /**
     * Excel导出
     * @param clazz 导出类
     * @param fileName 文件名
     * @param sheetName 工作表名
     * @param list 数据列表
     */
    public static <T> void excelExport(Class<T> clazz, String fileName, String sheetName, List<T> list) {
        try {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes == null) {
                throw new RuntimeException("无法获取HttpServletResponse");
            }
            
            HttpServletResponse response = requestAttributes.getResponse();
            if (response == null) {
                throw new RuntimeException("HttpServletResponse为空");
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            
            // 防止中文乱码
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName + ".xlsx");

            // 使用工作表名，如果为空则使用文件名
            String finalSheetName = (sheetName != null && !sheetName.trim().isEmpty()) ? sheetName : fileName;

            // 写入Excel
            EasyExcel.write(response.getOutputStream(), clazz)
                    .autoCloseStream(Boolean.FALSE)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet(finalSheetName)
                    .doWrite(list);

        } catch (IOException e) {
            throw new RuntimeException("Excel导出失败", e);
        }
    }

    /**
     * Excel导出（使用默认工作表名）
     * @param clazz 导出类
     * @param fileName 文件名
     * @param list 数据列表
     */
    public static <T> void excelExport(Class<T> clazz, String fileName, List<T> list) {
        excelExport(clazz, fileName, null, list);
    }
}
